<template>
<div class="vue_app" id="map_app" style="width:100%;height:100%;display:flex;align-items:center;justifyContent:space-between;">
	<div style='width:100%;background:white;'>
		<div>
			<div style="width:100%;height:2rem;" id="search">
				<div class="searchBar">
					<i class="icon njfont nj-sousuo" style="font-size: .75rem;margin: 0 .3rem;"></i>
					<input type="search" placeholder="请搜索地址" id="search-input" v-model="positionClue" style="-webkit-tap-highlight-color:transparent;border:none;background: white;height:100%;width:87%;outline:none;font-size: .75rem;">
					<div id="searchList"></div>
				</div>
			</div>
		</div>
	</div>
	<div class="assumeList" ref="assumeList">
		<ul ref="assumeListUL" style="font-size:.8rem;">
			<li v-for="(item, index) of positionList" :key="index" style="-webkit-tap-highlight-color:transparent;" @click="addParams.type ? AddLocation(item) : AddPosition(item)">
				<p v-if="item.inArea" style="color:black;opacity: .9;padding-top:.35rem;">{{item.name}}</p>
				<p v-if="item.inArea" style="color:black;opacity: .9;">{{item.district}}</p>
				<p v-if="!item.inArea" style="color:black;opacity: .4;padding-top:.35rem;">{{item.name}}</p>
				<p v-if="!item.inArea" style="color:black;opacity: .4;">{{item.district}}</p>
			</li>
		</ul>
	</div>
	<div class="legend_con" ref='legend_con'>
		<em></em><span>宁家鲜生配送范围</span><i></i>
	</div>
	<div id="allmap" style="width:100%;height:15rem;" ref="allmap" v-show='!showReload'>
		<!-- 鸡贼遮罩 -->
		<div class='SchemingShade' @click="HideSchemingShade" style='-webkit-tap-highlight-color:transparent;width:100%;height:100%;position:absolute;background:black;opacity:.4;z-index:2;' v-show="ShowShade"></div>
	</div>
	<!-- 地址推荐部分 -->
	<div class="address_search" ref="address_search" style="flex:1">
		<!-- 鸡贼遮罩 -->
		<div class='SchemingShade' @click="HideSchemingShade" style='-webkit-tap-highlight-color:transparent;width:100%;height:100%;position:absolute;background:black;opacity:.4;z-index:2;' v-show="ShowShade"></div>
		<div :class="ShowShade ? 'search-result-list-hidden' : 'search-result-list'" style="-webkit-overflow-scrolling:touch;padding-top:7px;">
			<ul style="margin: 0 .2rem;">
				<li v-for="(item, index) of shopList" style="-webkit-tap-highlight-color:transparent;" :class="{diselect:!item.isInArea}" @click="addParams.type ? addLocation(index, item) : AddPosition(item)" :key="index" ref="locationItem">
					<dl style='font-size:.75rem;'>
						<dt style='display: flex; justify-content: space-between;font-weight: bold;'>
							<span><img src="http://webapi.amap.com/theme/v1.3/markers/b/loc.png" v-if="item.flag" style="width:.7rem;height : .7rem;display:inline-block;margin-right:.3rem;"/>{{item.title}}</span><span>{{item.dis}}km</span>
						</dt>
						<dd style="text-align:left;margin: 0;margin-start:0;text-align:left;">
							{{item.addr}}
						</dd>
					</dl>
				</li>
			</ul>
		</div>
	</div>
	<div v-if="showReload" @click="reload" class="reload">点击刷新</div>
</div>
</template>
<script>
import axios from 'axios';
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex';
import {Toast} from "../../utils/toast";
import { showLoading ,hideLoading} from "../../utils/loading";
import getSearch from '../../utils/getUrlSearch';
import { CHANGE_NAVIGATION, LOCATION_INFO, CHOOSE_ADDRESS, CHOOSE_ADDRESS_ADD, EXIT_WEBVIEW, CHOOSE_ADDRESS_FROM_SHOPLIST } from '../../config/postMessage-types';

// let api = {
// 	customer_host: 'http://test.vmcustomer.scn.weilian.cn'
// }
export default {
	timer:null,
    props:{
        
	},
	data(){
		return{
			shopList:"",
			bounce:"",
			// isiOS: null,
			// isAndroid: null
			showReload: false,
			polygonList: [],     //存储可配送区域
			addParams: "",		 //是否从小周来
			positionList: [],    //联想列表
			positionClue: '',    //搜索关键字,
			ShowShade: false,    //是否显示遮罩
			areaList: [],
			storeList: [],
			reloadTimes: 0,
			map: undefined
		}
	},
    computed:{
        ...mapGetters( 'wxh',{
            login: "login",
            userInfo: 'userInfo',
            sessionId: 'sessionId'
		}),
		...mapGetters('qxz',{
			getBackTrigger: 'getBackTrigger'
		}),
		fromShopList() {
			return this.$route.query.fromShopList
		},
		storeCode() {
			return this.$route.query.storeCode
		},
		fromRN() {
			return this.$route.query.fromAddressControl ? true : false
		}
    },
    components:{
        
	},
	beforeRouteEnter(to, from, next){
		next();
	},
	methods:{
		//匹配storeCode
        matchStoreCode (storeId) {
            let storeCode;
            this.storeList.forEach(ele => {
				Number(ele.storeId) === Number(storeId) && (storeCode = ele.storeCode)
            })
            return storeCode;
		},
		// 开启中的storeId数组
        getVaildStoreIdList() {
            let tempArr = [];
            this.storeList.map(ele => {
                tempArr.push(JSON.stringify(ele.storeId))
            })
            return tempArr;
        },
		//获取门店列表
        async getStoreList(){
            var url = api.base_host + "/baseStore/getRestStore";
            let that = this;
            var params = {
                enterpriseCode: api.enterpriseCode
            }
            var config = {
                url: url,
                methods: "GET",
                params
            }
            let res = await axios(config);
            if(res.data.returnCode === 1){
				let arr = [];
                res.data.data[0].map(ele => {
                    if(ele.businessGoodsIsOpen && !ele.status) {
                        arr.push(ele)
                    }
                })
                that.storeList = arr;
                that.$store.dispatch('qxz/updateStoreList', res.data.data[0]);
            }
        },
		//发送地址给Rn
        sendAddToRn(obj) {
            let RnParams = {
                type: CHOOSE_ADDRESS,
                params: obj
			}
			console.log(RnParams,'RnParams')
			window.postMessage(JSON.stringify(RnParams));
			let goBackIns = {
				type: EXIT_WEBVIEW
			}
			window.postMessage(JSON.stringify(goBackIns));
		},
		// 发送地址给Rn，添加地址页面
		sendAddToRnAdd(obj) {
            let RnParams = {
                type: CHOOSE_ADDRESS_ADD,
                params: obj
            }
			window.postMessage(JSON.stringify(RnParams));
			let goBackIns = {
				type: EXIT_WEBVIEW
			}
			window.postMessage(JSON.stringify(goBackIns));
		},
		// shopList页面选择地址,发送给rn
		sendAddFromShopList (obj) {
			let RnParams = {
                type: CHOOSE_ADDRESS_FROM_SHOPLIST,
                params: obj
            }
			window.postMessage(JSON.stringify(RnParams));
		},
		AddLocation(item){
			var that = this;
			var geocoder = new AMap.Geocoder({
				city: "010"//城市，默认：“全国”
			});
			if(item.inArea){
				var lnglatXY=[item.location.lng, item.location.lat];
				geocoder.getAddress(lnglatXY, function(status, result) {
					if (status === 'complete' && result.info === 'OK') {
						//获得了有效的地址信息:
						var obj = {
							province: result.regeocode.addressComponent.province,
							city: result.regeocode.addressComponent.city,
							region: result.regeocode.addressComponent.district,
							address: item.address + ((item.address && !Array.isArray(item.address)) ? "-" : '') + item.name,
							positionlng: lnglatXY[0],
							positionlat: lnglatXY[1],
						}
						that.$store.dispatch('qxz/updateLocation', obj);
						localStorage.setItem("locateIn", JSON.stringify(obj));
						if(that.addParams.type != undefined){
							if(that.fromRN) {
								obj.type = that.addParams.type;
								//发送地址给RN
								that.sendAddToRnAdd(obj);
							}else {
								that.sendAddToRn(obj);
							}
							// if(that.addParams.type == "add"){
							// 	that.setaddFlagMutation(true);
							// }else{
							// 	that.setaddFlagMutation(false);
							// }
							// if(that.addParams.id != undefined){
							// 	that.$router.push({path:"addAddress",query:{obj:JSON.stringify(obj),id:that.addParams.id}});
							// }else{
							// 	if(that.addParams.toFrom != undefined){
							// 		that.$router.push({path:"addAddress",query:{obj:JSON.stringify(obj),toFrom:that.addParams.toFrom}});
							// 	}else{
							// 		that.$router.push({path:"addAddress",query:{obj:JSON.stringify(obj)}});
							// 	}
							// }
							return false
						}else{
							if (!that.sessionId) {
								// that.$router.push("login");
								return false;
							}else{
								
							}
						}

					} else {
						//获取地址失败
						Toast("fail", "获取此位置信息失败，请重试", 800);
					}
				});
			}else{
                Toast({
                    "message": "不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
		},
		addLocation(index, item){
			var that = this;
			var target = item;
			var geocoder = new AMap.Geocoder({
				city: "010"//城市，默认：“全国”
			});
			if(this.$refs.locationItem[index].className == "diselect"){
				Toast({
					duration:800,
					type:"warn",
					message:"不在配送范围内"
				})
			}else{
				var lnglatXY=[target.point.lng, target.point.lat];
				geocoder.getAddress(lnglatXY, function(status, result) {
					if (status === 'complete' && result.info === 'OK') {
						//获得了有效的地址信息:
						var obj = {
							province: result.regeocode.addressComponent.province,
							city: result.regeocode.addressComponent.city,
							region: result.regeocode.addressComponent.district,
							address: target.addr + (target.addr ? "-" : '') + item.title,
							positionlng: lnglatXY[0],
							positionlat: lnglatXY[1],
						}
						if(that.addParams.type != undefined){
							// return 
							if(that.fromRN) {
								obj.type = that.addParams.type;
								//发送地址给RN
								that.sendAddToRnAdd(obj);
							}else {
								that.sendAddToRn(obj);
							}
						}else{
							
						}
						//判断是否已有快速地址
						var localData = {
							address : result.regeocode.addressComponent,
							addName: result.regeocode.formattedAddress,
							isNew: true
						}
						// addressArr.push(localData); 
						// localStorage.setItem("quickAddress", JSON.stringify(addressArr));

						// Toast("success", "已添加至地址", 800);
						
						// setTimeout(function () {
						// 	history.back();
						// }, 800);

						//显示最新添加地址
						
						// if(localStorage.getItem("chooseAddressActiveIndex") != null){
						// 	localStorage.setItem("chooseAddressActiveIndex", 0);
						// }
						that.$store.dispatch('qxz/updateLocation', obj);
						localStorage.setItem("locateIn", JSON.stringify(obj));
						// that.$router.push({path:"chooseAddress"})
					} else {
						//获取地址失败
						Toast("fail", "获取此位置信息失败，请重试", 800);
					}
				});
			}
		},
		//添加联想列表地址
        AddPosition(item){
            if(item.inArea || item.isInArea){
                let that = this;
				let obj = new Object();
                AMap.service('AMap.Geocoder',function(){//回调函数
                    //实例化Geocoder
                    let geocoder = new AMap.Geocoder({
                        // city: "010"//城市，默认：“全国”
                    });
                    //TODO: 使用geocoder 对象完成相关功能
					var lnglatXY;//地图上所标点的坐标
					item.location ? lnglatXY = [item.location.lng , item.location.lat] : lnglatXY = [item.point.lng , item.point.lat];
                    geocoder.getAddress(lnglatXY, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                        //获得了有效的地址信息:
                        //即，result.regeocode.formattedAddress
                            obj.province = result.regeocode.addressComponent.province;
                            obj.city = result.regeocode.addressComponent.city || '市辖区';
							obj.region = result.regeocode.addressComponent.district;
							obj.address = result.regeocode.formattedAddress.split(result.regeocode.addressComponent.district)[1];
                            // obj.address = result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber + result.regeocode.addressComponent.township;
                            obj.positionlng = item.location ? item.location.lng : item.point.lng;
                            obj.positionlat = item.location ? item.location.lat : item.point.lat;
							obj.addressid = "-1";
							obj.storeCode = item.storeCode;
                            that.$store.dispatch('qxz/updateLocation', obj);
                            localStorage.setItem("locateIn", JSON.stringify(obj));
							localStorage.setItem("chooseAddressActiveIndex", null);
							console.log(obj)
							// 发给rn，更新信息
							if(that.fromShopList === 'fromShopList') {
								that.sendAddFromShopList(obj);
								return false
							}
							if(that.fromRN) {
								//发送地址给RN
								that.sendAddToRnAdd(obj);
							}else {
								that.sendAddToRn(obj);
							}
                        }else{
                        //获取地址失败
                        }
                    });
                })
                this.positionList = [];
				document.querySelector("#search-input").value = "";
            }else{
                Toast({
                    "message": "不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
		//出现异常，点击重新加载
		reload(){
			window.location.reload()
		},
		//判断设备类型
		judgePhoneType() {
		var u = navigator.userAgent;
			this.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
			this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		},
		//监听列表触摸事件
		touchList(){
			document.querySelector(".search-result-list").addEventListener("touchstart", () => {
			　　//软键盘弹出的事件处理
				if(this.isiOS){
					//解决ios设备提示框位置错乱
				}else{
					document.querySelector("#allmap").style.height = "50vh";
					document.querySelector(".search-result-list").style.height = "40vh";
					document.querySelector(".address_search").style.height = "50vh";
					let top = parseInt(document.querySelector("#search-input").getBoundingClientRect().top); //距离顶部的高度
					let height = document.querySelector("#search-input").offsetHeight + 3; //输入框自身的高度
					let offsetTop = top + height; //自动完成列表的偏移量
					document.querySelector(".amap-sug-result").style.top = `${offsetTop}px`;
					document.querySelector(".amap-sug-result").offsetHeight >= document.documentElement.clientHeight - offsetTop - 45 ? document.querySelector(".amap-sug-result").style.maxHeight = document.documentElement.clientHeight - offsetTop - 45 + 'px' : '';
				}
			}, false);
		},
		initScript() {
			//判断如果有script就删掉
			if (document.querySelector("#amap-box")){
				document.body.removeChild(document.querySelector("#amap-box"));
			}
			showLoading();
			setTimeout(() => {
				hideLoading();		
			},8000)
			let amapBox = document.createElement("div");
			amapBox.setAttribute("id", "amap-box");
			// this.initMap();
			let script1 = document.createElement("script");
			script1.onload = () => {
				let script2 = document.createElement("script");
				script2.onload = () => {
					setTimeout(() => {
						this.initMap();
					}, 500)
				}
				script2.src = "https://webapi.amap.com/ui/1.0/main.js";
				amapBox.insertAdjacentElement("beforeend", script2);
			};
			if(this.getIosVersion()){
				script1.src = 'https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
			}else {
				script1.src = 'https://webapi.amap.com/maps?v=1.4.6&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
			}
			amapBox.insertAdjacentElement("beforeend", script1);
			document.body.appendChild(amapBox);
		},
		//判断ios版本
        getIosVersion() {
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if (isAndroid) {
                return false//这个是安卓操作系统
            }
            if (isIOS) {//这个是ios操作系统
                var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                // ver = parseInt(ver[1], 10);
                var IosVersion = (ver[1] || '0') + (ver[2] || '0') + (ver[3] || '0');
                if(Number(IosVersion) < 935) {
                    return true
                }else {
                    return false
                }
            }
        },
		initMap(){
			var that = this;
			var adderssArr = [];
			if(localStorage.getItem("quickAddress")){
				var quickAdderss = JSON.parse(localStorage.getItem("quickAddress"));
				addressArr = addressArr.concat(quickAdderss);
			}
			var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
			var tenTimer;

			var shopLng;
			var shopLat;
			if(this.storeCode) {
				this.storeList.map(ele => {
					if(ele.storeCode == this.storeCode) {
						shopLng = ele.positionLng || 108.396208;
						shopLat = ele.positionLat || 22.811724;
					}
				})
			}else {
				shopLng = 108.396208;
				shopLat = 22.811724;
			}
			shop = createShopObject(shopLng, shopLat, "门店位置", 5000);
			//工厂模式，生成门店对象
			function createShopObject(lon, lat, name, radius) {
				var obj = {
					lon : lon,
					lat : lat,
					name : name,
					radius : radius
				}
				return obj;
			}
			//基础接口地址
			function getBaseUrl(){
				return api.local_host;
			}
			//监听搜索栏触摸事件
			this.TouchingSearcher();

			//监听列表触摸事件
			this.touchList();

			//高德地图
			//是否从个人中心添加收货地址
			let varibleCenter = (that.addParams.positionlat != undefined && that.addParams.positionlng != undefined);
			try{
				this.map = new AMap.Map('allmap', {
					resizeEnable: true,
					zoom: 15,
					center: varibleCenter ? [parseFloat(that.addParams.positionlng), parseFloat(that.addParams.positionlat)] : [108.383765, 22.813923],
					scrollWheel : true
				});
			} catch(err) {
				that.reloadTimes = that.reloadTimes + 1;
				if(that.reloadTimes < 3) {
					setTimeout(() => {
						that.initMap();
					},300)
					return
				}
				hideLoading();
				that.showReload = true;
				Toast({
					"message": "加载失败",
					"duration": 2000,
					"type" : "fail"
				})
				return false
			}
			//点击粉色条设置地图中心为当前门店
			// var resetMapCenter = that.$refs.legend_con; 
			// resetMapCenter.addEventListener('click', function() {
			// 	that.map.setCenter([shopLng, shopLat]);
			// }, false)
			//定位功能
			that.map.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
				//给一个定位过程的loading
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 5000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
				});
				//个人定位的marker
				var mineMarker = new AMap.Marker({
					icon: "https://webapi.amap.com/theme/v1.3/markers/b/loc.png",
					label : {
						offset: new AMap.Pixel(34, 17),//修改label相对于maker的位置
						content: "您的位置"
					}
				});
				that.map.addControl(geolocation);
				// setTimeout(function () {
				geolocation.getCurrentPosition();
				// }, 5000);
				
				//添加定位失败和定位成功的监听事件
				geolocation.on("complete", function (result) {
					//关闭loading效果
					hideLoading();
					clearTimeout(tenTimer);
					mineMarker.setPosition(new AMap.LngLat(result.position.lng, result.position.lat));	
					mineMarker.setMap(that.map);
					markerList.push(mineMarker);
					//根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别，参数overlayList默认为当前地图上添加的所有覆盖物图层
					that.map.setFitView(markerList);
					varibleCenter && that.map.setCenter([parseFloat(that.addParams.positionlng),parseFloat(that.addParams.positionlat)]);
				});
				geolocation.on("error", function () {
					//定位失败或者超过10秒后，关闭loading效果
					if (!tenSecond) {
						hideLoading();
						clearTimeout(tenTimer);
					}
				});
				//定义一个延时器，超过10秒提示定位失败，该方法是为了解决高德地图某些时候不执行定位失败的回调
				tenTimer = setTimeout(function () {
					hideLoading();
					tenSecond = true;
					clearTimeout(tenTimer);
					// suneeeUI.hideToast();
					// suneeeUI.showToast("fail", "定位失败，请刷新重试~", 1200);
				}, 6000);

				var auto = new AMap.Autocomplete ({

				});

				var placeSearch = new AMap.PlaceSearch({
					pageSize: 10,
					pageIndex: 1,
					map: that.map,
					autoFitView : true
				});
				placeSearch.on("complete", function () {
					
				});
				//给每个推荐地址的item添加点击事件
				var geocoder = new AMap.Geocoder({
					city: "010"//城市，默认：“全国”
				});
				var searchResultList = document.getElementsByClassName("search-result-list")[0];
				var searchResultListLi = searchResultList.getElementsByTagName("li");
				//滑动选址功能
				// setTimeout(() => {
					try{
						AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
							var positionPicker = new PositionPicker({
								mode: 'dragMap',
								map: that.map
							});
							positionPicker.start();
							//document.getElementsByClassName("amap-ui-misc-positionpicker")[0].children[0].style.display = "none";
							try{
								document.querySelector(".amap-ui-misc-positionpicker").children[0].setAttribute("src", "static/image/marker.png");
							}catch (err) {
								that.reloadTimes = that.reloadTimes + 1;
								if(that.reloadTimes < 3) {
									setTimeout(() => {
										that.initMap();
									},300)
									return
								}
								hideLoading();
								that.showReload = true;
								Toast({
									"message": "加载失败",
									"duration": 2000,
									"type" : "fail"
								})
								return false
							}
							// $(".amap-ui-misc-positionpicker-pin").hide();
							positionPicker.on('success', function(positionResult) {
								var maxNearPoi = 15;
								var lis = [];
								var allAddrs = [];
								// 当前点
								var currentAddr = {
									title: positionResult.address,
									addr: positionResult.nearestJunction,
									point: positionResult.position
								};
								// 获取附近的点
								var nearPoint = positionResult.regeocode.pois;
								var arr = [];
								for(var i = 0; i < maxNearPoi; i++) { // 取前 15个最近点
									if(nearPoint[i] != undefined){
										let point = nearPoint[i].location;
										//判断是否处于配送范围内,后台请求结果为公里
										if(varibleCenter){
											let lnglat = new AMap.LngLat(point.lng, point.lat);
										}
										let isInArea = false;
										
										that.polygonList.forEach((item,indent) => {
											let lnglat = new AMap.LngLat(point.lng, point.lat);
											if(item.contains(lnglat)) {
												isInArea = true;
												if(that.areaList.length) {
													nearPoint[i].storeCode = that.matchStoreCode(that.areaList[indent].deptid)
												}
											}
										})
										var mAddr = {
											title: nearPoint[i].name,
											point: nearPoint[i].location,
											addr: nearPoint[i].address,
											id: nearPoint[i].id,
											dis: calculate(nearPoint[i].location.lat, nearPoint[i].location.lng, shop.lat, shop.lon),
											isInArea: isInArea,
											storeCode: nearPoint[i].storeCode
										}
										var obj = {};
										obj.lat = nearPoint[i].location.lat;
										obj.lng = nearPoint[i].location.lng;
										arr.push(obj);
										mAddr.dis = mAddr.dis.toFixed(2);
										allAddrs.push(mAddr);
									}
								}
								//对地址数据做排序处理，从近到远
								that.shopList = sortAdd(allAddrs);
								function sortAdd (allAddrs){
									let dataLength = allAddrs.length;
									for(let i = 0; i < dataLength;i++){
										for(let j = i+1;j < dataLength;j++){
											if(allAddrs[i].dis > allAddrs[j].dis){
												let temp = allAddrs[i];
												allAddrs[i] = allAddrs[j];
												allAddrs[j] = temp;
											}
										}
									}
									let arr1 = [];
									let arr2 = [];
									for(let item of allAddrs){
										item.isInArea ? arr1.push(item) : arr2.push(item);
									}
									allAddrs = arr1.concat(arr2);
									return allAddrs;
								}
							});
						});
					}catch (err) {
						that.reloadTimes = that.reloadTimes + 1;
						if(that.reloadTimes < 3) {
							setTimeout(() => {
								that.initScript();
							},300)
							return
						}
						hideLoading();
						that.showReload = true;
						Toast({
							"message": "加载失败",
							"duration": 2000,
							"type" : "fail"
						})
						return false
					}
				// }, 5000)
				
				
				
				/*根据经纬度计算距离，单位是千米*/
				function calculate(lat1, lng1, lat2, lng2) {
					var radLat1 = lat1 * Math.PI / 180.0;
					var radLat2 = lat2 * Math.PI / 180.0;
					var a = radLat1 - radLat2;
					var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
					var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
					s = s * 6378.137;
					s = Math.round(s * 10000) / 10000;
					return s
				};
				/*给出结果*/
				function end(param1, param2) {
					var result = [];
					for(var i in param1) {
						for(var j in param2) {
							if(calculate(param1[i].lat, param1[i].lng, param2[j].lat, param2[j].lng) < param2[j].long) {
								result.push(i);
							}
						}
					}
					return result;
				}
			});
			//门店marker 将当前门店显示在地图上
			(function () {
				var isShow = false;
				if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
				}
				//请求配送范围的经纬度数组
                let url = api.tmsUrl + 'centralManagerApi/centralManagerObject';
				axios.post(url,{
					getAllBaselatticeByStoreId: {
						storeIdList: that.getVaildStoreIdList()
					}
				}).then(function (res) {
					that.polygonList = [];
					//门店配送范围
					let array = new Array();
					for(let item of res.data.data[0]){
						let Arr = new Array();
						for(let it of JSON.parse(item.longitudeandlatitude)){
							let arr = new Array();
							arr[0] = it.a;
							arr[1] = it.b;
							Arr.push(arr);
						}
						// if(that.storeCode) {
						// 	that.matchStoreCode(item.deptid) == that.storeCode && array.push(Arr);
						// 	that.matchStoreCode(item.deptid) == that.storeCode && that.areaList.push(item);
						// }else {
							array.push(Arr);
							that.areaList.push(item);
						// }
					}
					//多边形覆盖物节点坐标数组
					for (let item of array){
						var polygon = new AMap.Polygon({
							map: that.map,
							path: item,			//设置多边形边界路径
							strokeColor: "red", //线颜色
							strokeOpacity: 0, 	//线透明度
							strokeWeight: 0,    //线宽
							fillColor: "red", 	//填充色
							fillOpacity: 0		//填充透明度
						});
						polygon.setMap(that.map);
						that.polygonList.push(polygon);
					}
				})
				.catch(function (res) {
					
				});
				// 请求配送范围的经纬度数组
				let uri = api.tmsUrl + 'centralManagerApi/centralManagerObject';
				let option = {
					url: uri,
					method: 'post',
					data: {
						getAllStoreDistributionByStoreId: {
							storeIdList: that.getVaildStoreIdList()
						}
					}
				}
				axios(option).then(function (res) {
					//门店配送范围
					let array = new Array();
					for(let item of res.data.data[0]){
						let Arr = new Array();
						for(let it of JSON.parse(item.longitudeandlatitude)){
							let arr = new Array();
							arr[0] = it.a;
							arr[1] = it.b;
							Arr.push(arr);
						}
						// if(that.storeCode) {
						// 	that.matchStoreCode(item.deptid) == that.storeCode && array.push(Arr);
						// }else {
							array.push(Arr)
						// }
					}
					//多边形覆盖物节点坐标数组
					for (let item of array){
						var polygon = new AMap.Polygon({
							map: that.map,
							path: item,			//设置多边形边界路径
							strokeColor: "red", //线颜色
							strokeOpacity: 0,   //线透明度
							strokeWeight: 0,    //线宽
							fillColor: "red",   //填充色
							fillOpacity: 0.35   //填充透明度
						});
						polygon.setMap(that.map);
					}
				})
				.catch(function (res) {
					
				});
				//将门店配送范围显示在地图上
				var shopMarker = new AMap.Marker({
					// icon: "static/image/ning_store.png",
					position: [shop.lon, shop.lat],
					 icon: new AMap.Icon({            
						size: new AMap.Size(48, 48),  //图标大小
						image: "static/image/ning_store.png",
						imageSize: new AMap.Size(48,48),
						imageOffset: new AMap.Pixel(0, 0)
					}),        
					label : {
						offset: new AMap.Pixel(37, 28),//修改label相对于maker的位置
						content: shop.name
					}
				});
				// markerList.push(shopMarker);
				// shopMarker.setMap(that.map);
			})();
		},
		
		//搜索栏触摸事件
		TouchingSearcher(){
			document.querySelector("#search-input").addEventListener("focusin", () => {
				this.ShowShade = true;
			},false)
		},
		//收起遮罩
		HideSchemingShade(){
			this.ShowShade = false;
			this.positionList = [];
		},
		//搜索地址
        searchEvent(){
			var that = this;
            var auto = new AMap.Autocomplete ({
                
            });
            let autocomplete = new AMap.Autocomplete(auto);
            autocomplete.search(this.positionClue, (status, e) => {
				//TODO:开发者使用result自己进行下拉列表的显示与交互功能
                let assumeListUL = this.$refs.assumeListUL;
                let assumeList = this.$refs.assumeList;
                assumeList.style.maxHeight = this.clientHeight - 120 + "px";
                let Arr = new Array();
                let priorityList = new Array();
                let restList = new Array();
                e.tips && e.tips.forEach((item,index) => {
                    item.location && item.location.lng && Arr.push(item);
                },this)
                Arr.length && Arr.forEach((item,index) => {
                    this.polygonList.forEach((element,indent) => {
                        let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                        if(element.contains(lnglat)) {
							item.inArea = true;
							if(that.areaList.length) {
								item.storeCode = that.matchStoreCode(that.areaList[indent].deptid)
							}
						}
                    },this)
                },this)
                Arr.forEach(item => {
                    item.inArea ? priorityList.push(item) : restList.push(item);
                })
				let TerminalList = priorityList.concat(restList);
				this.positionList = TerminalList || [];
				console.log(this.positionList,'positionListpositionList')
            });
        },
		//重置自动完成列表的位置
		initAutoCompleteListOffsetTop() {
			this.isiOS && (() =>
			setTimeout(() => {
				clearTimeout(this.timer);
				let top = parseInt(document.querySelector("#search-input").getBoundingClientRect().top); //距离顶部的高度
				let height = document.querySelector("#search-input").offsetHeight + 3; //输入框自身的高度
				let offsetTop = top + height; //自动完成列表的偏移量
				let extraHeight = document.body.scrollTop;
				document.querySelector(".amap-sug-result").style.top = `${offsetTop + extraHeight}px`;
				document.querySelector(".amap-sug-result").style.left = `1.7rem`;
				document.querySelector(".amap-sug-result").style.overflowY = 'scroll';
				this.timer = setTimeout(() => {
					document.querySelector(".amap-sug-result").style.opacity = "1";
				}, 500);
			}, 0))();
			!this.isiOS && (() =>
			setTimeout(() => {
				let top = parseInt(document.querySelector("#search-input").getBoundingClientRect().top); //距离顶部的高度
				let height = document.querySelector("#search-input").offsetHeight + 3; //输入框自身的高度
				let offsetTop = top + height; //自动完成列表的偏移量
				document.querySelector(".amap-sug-result").style.top = `${offsetTop}px`;
				document.querySelector(".amap-sug-result").style.overflowY = 'scroll';
				document.querySelector(".amap-sug-result").offsetHeight >= document.documentElement.clientHeight - offsetTop - 45 ? document.querySelector(".amap-sug-result").style.maxHeight = document.documentElement.clientHeight - offsetTop - 45 + 'px' : '';
			}, 0))();
		},
		timerFn() {
			if (!document.querySelector(".amap-sug-result")) {
				setTimeout(() => {
					this.timerFn();
				}, 4);
			} else {
				document.querySelector(".amap-sug-result").style.maxHeight = document.documentElement.clientHeight - document.querySelector(".amap-sug-result").style.top - 2 + 'px';
			}
		},
		setShadeClickable (){
			if(document.querySelector(".loading-animation")){
				document.querySelector(".loading-animation").style.height = "80vh";
				document.querySelector(".loading-animation").style.top = "10vh";
			}else{
				setTimeout(() => {
					this.setShadeClickable();
				},300)
			}
		},
		calibrateListHeight() {
			let legend_con = this.$refs.legend_con.offsetHeight;
			let allmapHeight = this.$refs.allmap.offsetHeight;
			let address_search = this.$refs.address_search;
			address_search.style.height = document.documentElement.clientHeight - legend_con - allmapHeight - 45 + 'px';
		}
	},
	created() {
		let titleConfig = JSON.stringify({
            type: CHANGE_NAVIGATION,
            params: {
                title: "选择配送地址"
            }
        })
        setTimeout(() => {
            window.postMessage(titleConfig)
        },300)
		//判断设备类型
		this.judgePhoneType();
	},
    async mounted(){
		await this.getStoreList();
		this.addParams = this.$route.query;
		this.setShadeClickable();
		this.initScript();
		this.calibrateListHeight();
	},
	beforeDestroy(){
		// 处理抖动问题
		if(document.querySelector(".amap-sug-result")){
			document.body.removeChild(document.querySelector(".amap-sug-result"));
		}
		hideLoading()
	},
	watch:{
		positionClue(){
            this.searchEvent();
		},
		getBackTrigger(newVal) {
			this.map.destroy();
		}
	}
}
</script>
<style scoped>
.vue_app{
	height: 99%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-between;
	overflow: hidden;
}
.clear{
    clear:both;
}
ol,ul,li,dl{
    list-style: none;
    margin: 0;
    padding: 0;
}
p{
    margin: 0;
    padding: 0;
}
.address_search{
	width:100%;
	position: relative;
	border: 0;
}
.legend_con{
    height: 1.5rem;
    line-height: 1.5rem;
	z-index: 1;
	border-bottom: 1px solid rgba(234, 57, 57, 0.3);
    background: #fff2f2;
    padding: 0.2rem;
    width: 100%;
    vertical-align: top;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	position: static;
}
.legend_con>span{
    height: 100%;
	font-size: .75rem;
    line-height: 1.2rem;
}
.loading-animation{
	pointer-events:none;
}
.legend_con em {
	border: 2px dotted #ff3300;
	background: rgba(255, 0, 0, 0.2);
	margin-left: .4rem;
	width: 1rem;
	height: 1rem;
	margin-right: 0.5rem;
	border-radius: 100%;
	display: inline-block;
	float: left;
}
.reload{
	position: absolute;
	width: 25%;
	height: 1.5rem;
	line-height: 1.5rem;
	font-size: .7rem;
	border: 1px solid gray;  
	border-radius: .2rem;
	top:43%;
}
.search-result-list{
	overflow: visible;
	overflow-y: auto;
	width: 100%;
	height: 100%;
}
.search-result-list-hidden{
	overflow: hidden;
	width: 100%;
	height: 100%;
}
.search-result-list li{
	border-bottom: 1px solid #eaeaea;
    padding: 0.3rem 0;
}
.search-result-list li:nth-last-child(1){
	margin-bottom: 1.5rem;
}
.diselect{
	color: #ccc;
}
.auto-item{
	width:100%;
}
.assumeList{
    position: absolute;
    z-index: 3;
    left: 0;
    top: 2.3rem;
    width: 100%;
    overflow: hidden;
}
.assumeList ul{
    width: 100%;
}
.assumeList ul li{
    width: 100%;
    box-sizing: border-box;
    padding: 0 .7rem;
    height: 2.7rem;
    border-bottom: 1px solid #ccc;
    text-align: left;
    background: white;
}
.assumeList ul li p{
    width: 95%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.searchBar{
	width:94%;
	margin-left:3%;
	margin-top:.3rem;
	height:1.7rem;
	display:flex;
	align-items:center;
	justify-content:flex-start;
	border:1px solid #eaeaea;
	border-radius:.2rem;
}
.search-result-list li:nth-last-child(1){
	/* margin-bottom: 2.6rem; */
}
</style>
<style>
.amap-sug-result{
	position: absolute;
}
body{
    position: relative;
	height: '100%';
	overflow: hidden;
}

.amap-marker-label{
	font-weight:bold;
	border:none;
	background:none;
	font-size:14px;
	white-space: nowrap;
}
.amap-logo {
	right: 0 !important;
	left: auto !important;
	display: none !important;
}

.amap-copyright {
	right: 70px !important;
	left: auto !important;
	display: none !important;
}
.amap-geo{
	display: none !important;
}
</style>
